package Chapter2.Comparing.c9.Communication;

public class Container<T> {
    private T[] arr;

    private int top = 0;

    public Container() {
        this(5);
    }

    public Container(int size) {
        this.arr = (T[])new Object[size];
    }

    public synchronized void save(T o) {
        while(top == arr.length) {
            try {
                this.wait();
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        arr[top]=o;
        top++;
        /*try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        notify();
    }

    public synchronized T fetch() {
        while (top==0) {
            try{
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        top--;
        /*try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        T t = arr[top];
        notify();
        return t;

    }

    public int count(){
        return top;
    }
}
